package cn.edu.guet.springmvcdemo.dao.impl;
/*
 *   @Studio:CHJY · 源梦科技
 *   @Author:lzl
 *   @Ide:IntelliJ IDEA
 *   @Creation time:2021/7/4 16:45
 */

import cn.edu.guet.springmvcdemo.model.User;
import cn.edu.guet.springmvcdemo.dao.IUserDao;
import cn.edu.guet.springmvcdemo.util.DBConnection;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements IUserDao {
    @Override
    public List<User> viewAllUser() {
        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        List<User> userList=new ArrayList<>();
        try {
            conn= DBConnection.getConn();
            ps=conn.prepareStatement("select * from user");
            rs = ps.executeQuery();
            while(rs.next()){
                User user=new User();
                user.setUserId(rs.getString("userid"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                userList.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                rs.close();
                ps.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
        return userList;
    }

    @Override
    public void deleteUser(String userId) {
        Connection conn=null;
        PreparedStatement ps=null;
        conn=DBConnection.getConn();
        try{
            ps=conn.prepareStatement("delete from user where userId=?");
            ps.setString(1,userId);
            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                ps.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
